#!/bin/bash

# shellcheck source=meta-facebook/meta-harma/recipes-phosphor/gpio/phosphor-gpio-monitor/logging-util
source /usr/libexec/phosphor-gpio-monitor/logging-util

HELP="
Usage: power-rail-event-logger <event> <id_gpio-name>
<event> is the power rail event to log,
e.g. assert / deassert.

<id_gpio-name> is defined in json file,
e.g. 2_power-host-good
"

# get assert or deassert message
action=$1

# get gpio chip ID
MESSAGE=$2
number="${MESSAGE%%_*}"

# remove prefix from 0_xxxxxx to xxxxxx
GPIO_NAME="${MESSAGE#*_}"
EVENT_NAME="${GPIO_NAME#power-}"
EVENT_NAME="${EVENT_NAME%-good}"

MSG_ID="xyz.openbmc_project.State.Power.PowerRailFault"
DEVICE_PATH="/xyz/openbmc_project/inventory/system/board/Harma_MB/$EVENT_NAME"
STASH_FILE="/run/${GPIO_NAME}.log_entry"

if gpio_logging_valid "$number" "$action" ; then
    case $1 in
        "-h")
            echo "$HELP"
            ;;

        "assert")
            if [ ! -s "$STASH_FILE" ]; then
                 /usr/bin/log-create "$MSG_ID" --json \
                     "{ \"POWER_RAIL\": \"${DEVICE_PATH}\", \"FAILURE_DATA\": \"${GPIO_NAME}\"}" \
                     > "${STASH_FILE}"
            fi
            ;;

        "deassert")
            if [ -s "${STASH_FILE}" ]; then
                log-resolve -p "$(< "${STASH_FILE}")" && rm "${STASH_FILE}"
            fi
            ;;
    esac
fi

exit 0
